import { Navigate, useRoutes } from "react-router-dom";
import Login from "@/views/login";
import RootLayout from "@/layout";
import NotFound from "@/layout/404/NotFound";
import Register from "@/views/login/Register";
import { Suspense, lazy, useMemo } from "react";
import { useSelector } from "react-redux";
import { getMenus } from "@/utils/storage";
import { Spin } from "antd";
import Home from "@/views/dashboard";

const modules = import.meta.glob(['@/views/**/*.jsx']);

const basicRoutes = [
    {
        path: '/login',
        element: <Login />,
    },
    {
        path: '/register',
        element: <Register />
    },
    {
        path: '/',
        element: <Navigate to="/dashboard" />,
    },
    {
        path: '/404',
        element: <NotFound />
    },
    {
        element: <RootLayout />,
        children: [
            {
                path: '/dashboard',
                element: <Home />,
            },
            {
                path: "/*",
                element: <NotFound />,
            },
        ],
    },
];

// 动态路由
const buildRoutes = (menus) => {
    if (!menus || menus.length === 0) {
        return [];
    }
    return menus.flatMap(menu => {
        if (!menu.children || menu.children.length === 0) {
            let key = `/src/views${menu.path}.jsx`;
            if (!modules[key]) {
                key = `/src/views${menu.path}/index.jsx`;
            }
            if (!modules[key]) {
                return [];
            }
            const LazyComponent = lazy(modules[key]);
            return [{
                path: menu.path,
                element: (
                    <Suspense fallback={
                        <div style={{
                            display: 'flex',
                            justifyContent: 'center',
                            alignItems: 'flex-start',
                            height: '100vh',
                            paddingTop: '20%'
                        }}>
                            <Spin />
                        </div>
                    }>
                        <LazyComponent />
                    </Suspense>),
            }];
        }
        return buildRoutes(menu.children);
    });
}

const useAppRoutes = () => {
    const menuState = useSelector(state => state.menu.list);

    return useMemo(() => {
        const menus = getMenus();
        const dynamicRoutes = buildRoutes(menus);
        if (dynamicRoutes?.length > 0) {
            let router = {
                element: <RootLayout />,
                children: dynamicRoutes,
            }
            return [...basicRoutes, router];
        } else {
            return [...basicRoutes];
        }
    }, [menuState]);
};

const RootRoute = () => {
    const routes = useAppRoutes();
    return useRoutes(routes);
}

export default RootRoute;